using GEM.Application.Dto.File;
using GEM.Domain.Entities;
using GEM.Domain.Repositories;
using GEM.Application.Contracts.Storage;

namespace GEM.Application.Services;

public class FileService
{
    private readonly IFileRepository _fileRepository;
    private readonly IStorageProvider _storageProvider;
    public FileService(IFileRepository fileRepository, IStorageProvider storageProvider)
    {
        _fileRepository = fileRepository;
        _storageProvider = storageProvider;
    }

    public async Task<FileDto> UploadAsync(Stream fileStream, UploadFileDto dto)
    {
        var filePath = await _storageProvider.SaveAsync(fileStream, dto.FileName);
        var fileItem = new FileItem
        {
            Id = Guid.NewGuid(),
            FileName = dto.FileName,
            FilePath = filePath,
            Size = fileStream.Length,
            ContentType = dto.ContentType,
            OwnerId = dto.OwnerId
        };
        await _fileRepository.CreateAsync(fileItem);
        return new FileDto
        {
            Id = fileItem.Id,
            FileName = fileItem.FileName,
            FilePath = fileItem.FilePath,
            Size = fileItem.Size,
            ContentType = fileItem.ContentType,
            OwnerId = fileItem.OwnerId
        };
    }

    public async Task<Stream?> DownloadAsync(Guid fileId)
    {
        var file = await _fileRepository.GetByIdAsync(fileId);
        if (file == null) return null;
        return await _storageProvider.GetAsync(file.FilePath);
    }

    public async Task DeleteAsync(Guid fileId)
    {
        var file = await _fileRepository.GetByIdAsync(fileId);
        if (file == null) return;
        await _storageProvider.DeleteAsync(file.FilePath);
        file.IsDeleted = true;
        await _fileRepository.UpdateAsync(file);
    }
}
